// 用来存放事件
const eventMap = {}
const eventOnceMap = {}

const on = (name,fn,buff)=>{
  buff[name] = buff[name] || {}
  const id = window.$uuid()
  buff[name][id] = fn
  return id
}
const emit = (name,data,buff) =>{
  const eventList = buff[name]
  if(eventList){
    for(var key in eventList){
      const fn = eventList[key]
      try {
        fn && fn(data)
      } catch (error) {
        console.error(error)
      }
    }
  }
}
const off = (name,id,buff)=>{
  if(id){
    const eventList = buff[name]
    if(buff[name] && eventList[id]){
      delete eventList[id]
    }
  }
  else{
    if(buff[name]){
      delete buff[name]
    }
  }
}

const onEvent = (name,fn)=>{
  return on(name,fn,eventMap)
}

const onOnceEvent = (name,fn)=>{
  return on(name,fn,eventOnceMap)
}

const emitEvent = (name,data) =>{
  emit(name,data,eventMap)
  emit(name,data,eventOnceMap)
  delete eventOnceMap[name]
}

const offEvent = (name,id) =>{
  off(name,id,eventMap)
  off(name,id,eventOnceMap)
}

const removeAllEvent = ()=>{
  for(let key in eventMap){
    delete eventMap[key];
  }
  for(let key in eventOnceMap){
    delete eventOnceMap[key];
  }
}

export {
  onEvent,
  onOnceEvent,
  emitEvent,
  offEvent,
  removeAllEvent
}


